<template>
    <div class="container">
      <el-button type="primary" @click="goBack">返回角色列表</el-button>
      
      <el-divider>当前角色：{{ currentRole.roleName }}（{{ currentRole.roleKey }}）</el-divider>
      
      <div class="assignment-container">
        <div class="current-permissions">
          <h3>已分配权限（{{ assignedPermissions.length }}个）</h3>
          <el-table :data="assignedPermissions" height="400" empty-text="暂无权限">
            <el-table-column prop="permissionName" label="权限名称"/>
            <el-table-column prop="permissionCode" label="权限标识"/>
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button size="small" type="danger" 
                  @click="removePermission(row.permissionId)">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
  
        <div class="available-permissions">
          <div class="search-header">
            <h3>可用权限（{{ filteredAvailablePermissions.length }}个）</h3>
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="输入权限名称或标识"
                clearable
                suffix-icon="Search"
                @keyup.enter="handleSearch"
              />
            </div>
          </div>
          <el-table :data="filteredAvailablePermissions" height="400" empty-text="没有匹配的权限">
            <el-table-column prop="permissionName" label="权限名称"/>
            <el-table-column prop="permissionCode" label="权限标识"/>
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button size="small" type="primary" 
                  @click="assignPermission(row.permissionId)">
                  分配
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { 
    getRolePermissions, 
    addRolePermission, 
    removeRolePermission 
  } from '@/api/rolePermissionApi'
  import { getPermissions } from '@/api/permissionApi'
  import { getRoleById } from '@/api/roleApi'
  
  const route = useRoute()
  const router = useRouter()
  const roleId = parseInt(route.params.roleId)
  
  // 响应式数据
  const currentRole = ref({})
  const allPermissions = ref([])
  const assignedPermissions = ref([])
  const availablePermissions = ref([])
  const searchKeyword = ref('')
  
  // 计算属性：过滤可用权限
  const filteredAvailablePermissions = computed(() => {
    if (!searchKeyword.value.trim()) return availablePermissions.value
    
    const keyword = searchKeyword.value.trim().toLowerCase()
    return availablePermissions.value.filter(p => 
      p.permissionName.toLowerCase().includes(keyword) || 
      p.permissionCode.toLowerCase().includes(keyword)
    )
  })
  
  // 初始化加载数据
  onMounted(async () => {
    try {
      await loadRoleData()
      await loadAllPermissions()
      await loadRolePermissions()
    } catch (error) {
      ElMessage.error('数据加载失败')
      console.error('加载错误:', error)
    }
  })
  
  // 加载角色信息
  const loadRoleData = async () => {
    const res = await getRoleById(roleId)
    currentRole.value = res.data
  }
  
  // 加载所有权限
  const loadAllPermissions = async () => {
    const res = await getPermissions({ page: 1, size: 1000 }) // 假设分页获取全部
    allPermissions.value = res.data.content || []
  }
  
  // 加载角色权限
  const loadRolePermissions = async () => {
    const res = await getRolePermissions(roleId)
    const assignedIds = res.data.map(rp => rp.permissionId)
    
    // 分离已分配和未分配权限
    assignedPermissions.value = allPermissions.value
      .filter(p => assignedIds.includes(p.permissionId))
    availablePermissions.value = allPermissions.value
      .filter(p => !assignedIds.includes(p.permissionId))
  }
  
  // 分配权限
  const assignPermission = async (permissionId) => {
    try {
      await addRolePermission({ roleId, permissionId })
      await reloadData()
      ElMessage.success('权限分配成功')
    } catch (error) {
      ElMessage.error('分配失败: ' + (error.response?.data?.message || '未知错误'))
    }
  }
  
  // 移除权限
  const removePermission = async (permissionId) => {
    try {
      await removeRolePermission(roleId, permissionId)
      await reloadData()
      ElMessage.success('权限移除成功')
    } catch (error) {
      ElMessage.error('移除失败: ' + (error.response?.data?.message || '未知错误'))
    }
  }
  
  // 重新加载数据
  const reloadData = async () => {
    await Promise.all([loadAllPermissions(), loadRolePermissions()])
  }
  
  // 返回角色列表
  const goBack = () => {
    router.push({ name: 'role-management' })
  }
  
  // 处理搜索
  const handleSearch = () => {
    // 搜索逻辑已通过计算属性自动处理
  }
  </script>
  
  <style scoped>
  .container {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
  }
  
  .assignment-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
    margin-top: 20px;
  }
  
  .current-permissions,
  .available-permissions {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    height: 65vh;
    display: flex;
    flex-direction: column;
  }
  
  .search-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    gap: 15px;
  }
  
  .search-box {
    flex: 1;
    max-width: 300px;
  }
  
  h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
    font-weight: 600;
  }
  
  .el-table {
    flex: 1;
    margin-top: 10px;
  }
  
  .el-table :deep(.cell) {
    padding: 0 8px;
  }
  
  .el-divider {
    margin: 20px 0;
  }
  </style>